require("gang28enum")
local tabletool = require "tabletool"
local gang28 = {}

-- 40张牌编码
local cardskey = {
    1,2,3,4,        -- 1
    5,6,7,8,        -- 2
    9,10,11,12,     -- 3
    13,14,15,16,    -- 4
    17,18,19,20,    -- 5
    21,22,23,24,    -- 6
    25,26,27,28,    -- 7
    29,30,31,32,    -- 8
    33,34,35,36,    -- 9
    37,38,39,40,    -- 白板
}
-- 编码对应的牌
local cardsvalue = {
    1,1,1,1,
    2,2,2,2,
    3,3,3,3,
    4,4,4,4,
    5,5,5,5,
    6,6,6,6,
    7,7,7,7,
    8,8,8,8,
    9,9,9,9,
    10,10,10,10,
}

gang28.shuffle = function(d)
    d.initcards = tabletool.deepcopy(cardskey)
    -- 对牌池中的牌洗牌
    local r = 1
    for i = 1, #d.initcards do
        r = math.random(#d.initcards + 1 - i)
        d.initcards[r], d.initcards[#d.initcards + 1 - i] = d.initcards[#d.initcards + 1 - i], d.initcards[r]
    end
end

gang28.sort = function(cards)
    if cards[1] < cards[2] then
        cards[1], cards[2] = cards[2], cards[1]
    end
end

gang28.cardtype = function(cards)
    local cv1, cv2 = cardsvalue[cards[1]], cardsvalue[cards[2]]
    if cv1 == cv2 then
        return ECardType.CARD_TYPE_PAIR
    elseif cv1 == 8 and cv2 == 2 then
        return ECardType.CARD_TYPE_28
    end
    return ECardType.CARD_TYPE_UNKNOW
end

gang28.cardvalue = function(cards)
    return (cardsvalue[cards[1]] + cardsvalue[cards[2]]) % 10
end

gang28.compare = function(lcards, rcards)
    local lt = gang28.cardtype(lcards)
    local rt = gang28.cardtype(rcards)
    if lt == rt then
        if lt == ECardType.CARD_TYPE_PAIR then
            return cardsvalue[lcards[1]] >= cardsvalue[rcards[1]]
        elseif lt == ECardType.CARD_TYPE_28 then
            return true
        else
            local lcv = gang28.cardvalue(lcards)
            local rcv = gang28.cardvalue(rcards)
            if lcv == rcv then
                if lcv == 0 then return true end
                return cardsvalue[lcards[1]] >= cardsvalue[rcards[1]]
            else
                return lcv > rcv
            end
        end
    else
        return lt > rt
    end
end

gang28.gettimes = function(cards)
    local cardtype = gang28.cardtype(cards)
	local cardvalue = gang28.cardvalue(cards)
    local times = 1
    
	if cardtype == ECardType.CARD_TYPE_PAIR then
		if cardsvalue[cards[1]] == 10 then
			times = 5
		else
			times = 4
		end
	elseif cardtype == ECardType.CARD_TYPE_28 then
		times = 3
	else
		if cardvalue > 7 then
			times = 2
		end
    end
    return times
end

return gang28